<?php
/**
 * Name: 客户资源控制器类.
 * User: 董坤鸿
 * Date: 2016/10/11
 * Time: 15:08
 */

namespace App\Http\Controllers\Resources;

use App\Http\Requests\CustomerRequest;
use App\Models\AcceptRecord;
use App\Models\Customer;
use App\Models\Group;
use App\Models\HouseInfo;
use App\Models\Project;
use App\Models\User;
use App\Services\AdminService;
use App\Services\HelpService;
use App\Services\ServiceFactory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\Interfaces\RepoServiceInterface;
use Auth;

class CustomerController extends Controller
{
    /**
     * 初始化
     * CustomerController constructor.
     * @param ServiceFactory $_repoService
     */
    public function __construct($_resource)
    {
        $this->_resource = $_resource;
    }

    /**
     * 客户资源列表
     * @return mixed
     */
    public function index()
    {
        //当前登录用户为操作员的话,无权限创建
        //$this->authorize(new Customer());
        $data = $this->_repoService()->read();
        if (!empty($data))
            return $data;
        else
            return [];
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //当前登录用户为操作员的话,无权限创建
       $this->authorize('create', new Customer());
    }

    /*
     * Store a newly created resource in storage.
     * 这几个接口的代码, 希望后期有时间可以优化下, 时间紧迫, 现在只能先完成功能
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CustomerRequest $request)
    {
        $user = Auth::User();
        // 如果是上级账号, 新建客户 必须指定项目和负责人(project_id和user_id)
        // 如果当前登录的账号没有负责项目, 则是上级账号
        $pro_id = Project::where('users', $user->id)
            ->get()
            ->pluck('_id')
            ->all();
        
        $data = $request->all();
        $data = HelpService::getRequest($data);
        $isNew = true;
        $data['company_id'] = $user->company_id;
        // 如果没有project_id, 则根据当前登录用户找到负责的项目
        if (empty($data['project_id'])) {
            $project_id = Project::whereIn('users', [$user->id])
                ->get()
                ->pluck('id')
                ->all();
            if (!empty($project_id)) {
                $data['project_id'] = $project_id[0];
            } else {
                return $this->_error('此用户没有负责的项目');
            }
        }
        if (!empty($data['customer']['baseInfo']['name'])) {
            // 提交过来的项目必须存在
            $project = Project::find($data['project_id']);
            if (is_null($project)) {
                return $this->_error('此项目不存在');
            }
            // 为空,说明是上级账号
            if (empty($pro_id)) {
                // 传递过来项目的group_id
                $pro_group_id = $project->group_id;
                $group_id = $user->group_id;
                $group = new Group();
                $groups = $group->getLeafBy($group_id);
                $ids = array_column($groups, '_id');
                if (!in_array($pro_group_id, $ids)) {
                    return $this->_error('此账号下面没有此项目!');
                }
                // pc端上级账号新增客户
                if (!empty($data['user_id']) && !in_array($data['user_id'], $project->users)) {
                    return $this->_error('项目的负责人必须是提交过来的user_id');
                }
                // 如果账号被禁用, 则不能创建客户
                $tempUser = User::find($data['user_id']);
                if (is_null($tempUser)) {
                    return $this->_error("用户不存在!");
                }
                $status = $tempUser->status;
                if ($status === 0) {
                    return $this->_error("账号被禁用!");
                }
            } else {
                // 提交过来的项目id 的负责人必须是当前登录的人
                if (!in_array($user->id, $project->users)) {
                    return $this->_error('项目的负责人必须是当前登录的用户');
                }
                // 账号被禁用, 则不能创建客户
                $currentStatus= $user->status;
                if ($currentStatus === 0) {
                    return $this->_error("账号被禁用!");
                }
            }
            $data['projects'] = array($data['project_id']);
            unset($data['project_id']);
            // 新增时 如果房屋信息不为空 则修改房屋信息格式 每套房屋增加一个id
            if (array_key_exists('houseInfo', $data['customer'])) {
                if (!empty($houseData = $data['customer']['houseInfo'])) {
                    // 重新组合的数组
                    $arr = [];
                    $adds = [];
                    foreach ($houseData as $v) {
                        if (!empty($v)) {
                            if (!empty($v['最近装修时间'])) {
                                $v['最近装修时间'] = strtotime($v['最近装修时间']);
                            }
                            if (!empty($v['租赁时间'])) {
                                $v['租赁时间'][0] = strtotime($v['租赁时间'][0]);
                                $v['租赁时间'][1] = strtotime($v['租赁时间'][1]);
                            }
                            // 检查地址是否重复, 重复的跳过
                            if (!empty($v['address'])) {
                                $add_str = implode(',', $v['address']);
                                if (in_array($add_str, $adds)) {
                                    continue;
                                }
                                array_push($adds, $add_str);
                            }
                            $houseModel = new HouseInfo();
                            $houseInfo = $houseModel->create($v);
                            array_push($arr, $houseInfo);
                        }
                    }
                    $data['customer']['houseInfo'] = $arr;
                }
            }
            //客户姓名+手机号查重
            if (!empty($data['customer']['baseInfo']['name']) && !empty($data['customer']['baseInfo']['mobile'])){
                $checkCustomer = Customer::where([
                    'baseInfo.mobile' => $data['customer']['baseInfo']['mobile'],
                ])->first();
                if ($checkCustomer && $checkCustomer->baseInfo['name'] === $data['customer']['baseInfo']['name']) {
                    $isNew = false;
                } else if ($checkCustomer) {
                    return $this->_error('mobile:手机号已存在');
                }
            }
            //如果用户不存在则新建，存在将客户新增至传入项目中
            if ($isNew) {
                if (isset($data['customer']['baseInfo'])) {
                    $data['baseInfo'] = $data['customer']['baseInfo'];
                    if (!empty($data['customer']['baseInfo']['birthday'])) {
                        $data['baseInfo']['birthday'] = strtotime($data['customer']['baseInfo']['birthday']);
                    }
                    if (!empty($data['customer']['baseInfo']['driverAt'])) {
                        $data['baseInfo']['driverAt'] = strtotime($data['customer']['baseInfo']['driverAt']);
                    }
                }
                if (isset($data['customer']['houseInfo'])) {
                    $data['houseInfo'] = $data['customer']['houseInfo'];
                }
                if (isset($data['customer']['houseBuy'])) {
                    $data['houseBuy'] = $data['customer']['houseBuy'];
                    if (empty($data['houseBuy'])) {
                        unset($data['houseBuy']);
                    }
                }
                if (isset($data['customer']['socialInfo'])) {
                    $data['socialInfo'] = $data['customer']['socialInfo'];
                    if (!empty($data['customer']['socialInfo']['shihui']['regDate'])) {
                        $data['socialInfo']['shihui']['regDate'] = strtotime($data['customer']['socialInfo']['shihui']['regDate']);
                    }
                    // socialInfo里面都为空,删除此字段 (app的格式不对)
                    if (array_key_exists("shihui", $data['socialInfo'])) {
                        if (empty($data['socialInfo']['shihui'])) {
                            unset($data['socialInfo']['shihui']);
                        }
                    }
                    if (array_key_exists("weibo", $data['socialInfo'])) {
                        if (empty($data['socialInfo']['weibo'])) {
                            unset($data['socialInfo']['weibo']);
                        }
                    }
                    if (array_key_exists("wechat", $data['socialInfo'])) {
                        if (empty($data['socialInfo']['wechat'])) {
                            unset($data['socialInfo']['wechat']);
                        }
                    }
                    if (empty($data['socialInfo'])) {
                        unset($data['socialInfo']);
                    }
                }
                // 新增时,标签去重
                if (isset($data['customer']['tags'])) {
                    $data['tags'] = array_values(array_unique($data['customer']['tags']));
                }
                unset($data['customer']);
                $data['company_id'] = $user->company_id;
                $res = $this->_repoService()->create($data);
            } else {
                $projects = $checkCustomer->projects;
                if(in_array($data['projects'][0], $projects)){
                    return $this->_error('该客户已存在，不可重复添加');
                } else {
                    $projects = $checkCustomer->projects;
                    $projects = array_merge($projects, $data['projects']);
                    $oldHouseInfo = $checkCustomer->houseInfo;
                    // 数据库查出来的地址
                    $old_arr = [];
                    if (!empty($oldHouseInfo)) {
                        $address = array_column($oldHouseInfo, 'address');
                        foreach ($address as $v) {
                            $v1 = implode(',', $v);
                            array_push($old_arr, $v1);
                        }
                    }
                    // 要保存到数据库中的房屋信息
                    $arr = [];
                    if (!empty($data['customer']['houseInfo'])) {
                        foreach ($data['customer']['houseInfo'] as $v2) {
                            $v3 = implode(',', $v2['address']);
                            if (in_array($v3, $old_arr)) {
                                unset($v2);
                                continue;
                            }
                            array_push($arr, $v2);
                        }
                    }
                    $houseInfo = array_merge($oldHouseInfo, $arr);
                    $checkCustomer->projects = $projects;
                    $checkCustomer->houseInfo = $houseInfo;
                    $checkCustomer->save();
                    $res = $checkCustomer;
                }
            }
            // 认领 下级账号自动认领, 上级账号指定负责人认领
            // 当前登录账号没有负责项目, 则是上级账号
            if (empty($pro_id)) {
                if (empty($data['user_id'])) {
                    return $this->_error('没有传递项目负责人字段');
                }
                $filter['user_id'] = $data['user_id'];
            } else {
                $filter['user_id'] = $user->id;
            }
            $filter['project_id'] = $data['projects'][0];
            $filter['customer_id'] = $res->id;
            $filter['company_id'] = $user->company_id;
            //调用更新认领表逻辑
            $admin_service = new AdminService();
            $admin_service->updateAcceptRecord($filter);
            return $this->_repoService()->find(['id' => $res->_id]);
        } else {
            return $this->_error('姓名不能为空');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        //当前登录用户为操作员的话,无权限创建
        //$this->authorize('show', new Customer());
        $user = Auth::User();
        $customer = Customer::find($id);
        // 当前用户负责的项目
        $project_ids = Project::whereIn('users', [$user->id])
            ->get()
            ->pluck('id')
            ->all();
        // 如果没有负责限项目, 说明是上级账号  app端,如果当前登录的用户没有负责项目, 则不让他登录
        // 上级账号能看到group_id下级的所有项目的客户
        if (empty($project_ids)) {
            $group_id = $user->group_id;
            $group = new Group();
            $groups = $group->getLeafBy($group_id);
            $group_ids = [];
            foreach ($groups as $v) {
                array_push($group_ids, $v->id);
            }
            $project_ids = Project::whereIn('group_id', $group_ids)->get()->pluck('_id')->all();
            //dd($project_id);
            // 获取会员的所有项目id
            if (!is_null($customer)) {
                $projects = $customer->projects;
                //dd($projects);
                // 判断此客户所属的项目是否含有上级账号下属的项目
                $pro_arr = [];
                foreach ($projects as $p) {
                    if (in_array($p, $project_ids)) {
                        array_push($pro_arr, $p);
                    }
                }
                if (empty($pro_arr) || count($pro_arr) === 0) {
                    return $this->_error("没有权限显示此客户");
                }
                $result = $this->_repoService()->find(['id'=>$id]);
                return $result;
            } else {
                return $this->_error('没有此会员');
            }
        }
        // 此处是下级账号
        $project_id = $project_ids[0];
        // 如果客户没有被认领, 则无权限查看此客户
        $isRecord = AcceptRecord::where([
            'customers' => $id,
            'project_id' => $project_id
        ])->first();
        if (is_null($isRecord)) {
            return $this->_error('此客户没有被认领,不能查看');
        }
        // 如果不是主管,只能查看自己认领的客户详情
        if (!$user->isManager) {
            $hasRecord = AcceptRecord::where([
                'user_id' => $user->id,
                'customers' => $id,
                'project_id' => $project_id
            ])->first();
            if (is_null($hasRecord)) {
                return $this->_error('没有权限查看此客户');
            }
        }
        // 获取会员的所有项目id
        if (!is_null($customer)) {
            $projects = $customer->projects;
            // 当前用户负责的项目id在会员所有项目id中,就有权限查看
            if (in_array($project_id, $projects)) {
                $result = $this->_repoService()->find(['id'=>$id]);
                return $result->merge();
                //return $result;
            } else {
                return $this->_error('没有权限显示此客户');
            }
        } else {
            return $this->_error('没有此会员');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //当前登录用户为操作员的话,无权限创建
        $this->authorize('edit', new Customer());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(CustomerRequest $request, $id) {
        $user = Auth::User();
        $customer = Customer::find($id);
        // 权限判断
        // 当前用户负责的项目
        $project_ids = Project::whereIn('users', [$user->id])
            ->get()
            ->pluck('_id')
            ->all();
        // 为空 说明是上级账号
        if (empty($project_ids)) {
            //return $this->_error('此用户没有负责的项目');
            $group_id = $user->group_id;
            $group = new Group();
            $groups = $group->getLeafBy($group_id);
            $group_ids = [];
            foreach ($groups as $v) {
                array_push($group_ids, $v->id);
            }
            $project_ids = Project::whereIn('group_id', $group_ids)->get()->pluck('_id')->all();
//            $shhKey = Project::whereIn('group_id', $group_ids)->get()->pluck('plugins.shihui.key')->all();
            // 获取会员的所有项目id
            if (!is_null($customer)) {
                $projects = $customer->projects;
                // 判断此客户所属的项目是否含有上级账号下属的项目
                $pro_arr = [];
                foreach ($projects as $p) {
                    if (in_array($p, $project_ids)) {
                        array_push($pro_arr, $p);
                    }
                }
                if (empty($pro_arr) || count($pro_arr) === 0) {
                    return $this->_error("没有权限编辑此客户");
                }
            } else {
                return $this->_error('没有此会员');
            }
        } else {
            $project_id = $project_ids[0];
            $project = Project::find($project_id);
//            $plugins = $project->plugins;
//            if (!empty($plugins)) {
//                $shhKey = array($plugins['shihui']['key']);
//            } else {
//                return $this->_error('此项目不是实惠项目');
//            }
            // 如果客户没有被认领, 则无权限修改此客户
            $isRecord = AcceptRecord::where([
                'customers' => $id,
                'project_id' => $project_id
            ])->first();
            if (is_null($isRecord)) {
                return $this->_error('此客户没有被认领,不能编辑');
            }
            // 如果不是主管,只能编辑自己认领的客户
            if (!$user->isManager) {
                $hasRecord = AcceptRecord::where([
                    'user_id' => $user->id,
                    'customers' => $id,
                    'project_id' => $project_id
                ])->first();
                if (is_null($hasRecord)) {
                    return $this->_error('没有权限编辑此客户');
                }
            }
            // 获取客户的所有项目
            $projects = $customer->projects;
            if (!in_array($project_id, $projects)) {
                return $this->_error('没有权限编辑此客户');
            }
        }
        $data = $request->all();
        // 如果房屋信息不为空, 修改房屋信息的业务逻辑
        if (!empty($data['houseInfo'])) {
            $houseInfo = [];
            // 获取会员房屋信息的所有地址
            $address_arr = [];
            $customer = Customer::find($id);
            if (!is_null($customer)) {
                $attr = $customer->getAttributes();
                if (array_key_exists('houseInfo', $attr)) {
                    $house = $customer->houseInfo;
                    foreach ($house as $one) {
                        if (!empty($one['address'])) {
                            array_push($address_arr, $one['address']);
                        }
                    }
                }
            } else {
                return $this->_error('没有此会员');
            }
            foreach ($data['houseInfo'] as $v) {
                if (!empty($v) && !empty($v['address'])) {
                    if (!empty($v['最近装修时间'])) {
                        $v['最近装修时间'] = strtotime($v['最近装修时间']);
                    }
                    if (!empty($v['租赁时间'])) {
                        $v['租赁时间'][0] = strtotime($v['租赁时间'][0]);
                        $v['租赁时间'][1] = strtotime($v['租赁时间'][1]);
                    }
                    // 没有id,说明是新增, 得判断地址是否存在
                    if (!array_key_exists('_id', $v) && !in_array($v['address'], $address_arr)) {
                        $houseModel = new HouseInfo();
                        $houseData = $houseModel->create($v);
                        array_push($houseInfo, $houseData);
                        array_push($address_arr, $v['address']);
                        continue;
                    }
                    // 没有id,说明是新增, 得判断地址是否存在
                    if (!array_key_exists('_id', $v) && in_array($v['address'], $address_arr)) {
                        if (HelpService::fromApp()) {
                            return $this->_error("st@,@"."房屋信息已存在,请勿重复添加");
                        } else {
                            return $this->_error("房屋信息有重复");
                        }
                    }
                    $arr_house = HelpService::groupHouse($id);
                    // 有id说明是修改
                    if (array_key_exists('_id', $v)) {
                        if ($arr_house[$v['_id']] !== $v['address'] && in_array($v['address'], $address_arr)) {
                            //return $this->_error("st@,@"."房屋信息已存在,请勿重复添加");
                            if (HelpService::fromApp()) {
                                return $this->_error("st@,@"."房屋信息已存在,请勿重复添加");
                            } else {
                                return $this->_error("房屋信息有重复");
                            }
                        }
                        $houseModel = new HouseInfo();
                        $house = $houseModel->update($v, $id);
                        if (!empty($house) && $house != 1) {
                            // 修改已经存在的数据
                            $houseInfo = array_merge($houseInfo, $house);
                            array_push($address_arr, $v['address']);
                            continue;
                        }

                        if (empty($house)) {
                            return $this->_error('数据有问题');
                        }
                    }
                }
            }
            $data['houseInfo'] = $houseInfo;
            // 修改时id都存在, 如果地址被改为一样,则提示错误
            $arr = [];
            foreach ($data['houseInfo'] as $v) {
                array_push($arr, implode(',' ,$v['address']));
            }
            if (count($arr) != count(array_unique($arr))) {
                return $this->_error("st@,@"."房屋信息已存在,请勿重复添加");
            }
        }
        // 传递过来的数据为空的话 删掉
        if (empty($data['baseInfo'])) {
            unset($data['baseInfo']);
        }
        if (empty($data['houseBuy']['区域'])) {
            unset($data['houseBuy']['区域']);
        }
        if (empty($data['houseBuy'])) {
            unset($data['houseBuy']);
        }
        if (empty($data['socialInfo']['shihui'])) {
            unset($data['socialInfo']['shihui']);
        }
        if (empty($data['socialInfo']['weibo'])) {
            unset($data['socialInfo']['weibo']);
        }
        if (empty($data['socialInfo']['wechat'])) {
            unset($data['socialInfo']['wechat']);
        }
        if (empty($data['socialInfo'])) {
            unset($data['socialInfo']);
        }
        // 标签去重
        if (!empty($data['tags'])) {
            $data['tags'] = array_values(array_unique($data['tags']));
        }
        // 把时间转为时间戳
        if (isset($data['baseInfo'])) {
            if (!empty($data['baseInfo']['birthday'])) {
                $data['baseInfo']['birthday'] = strtotime($data['baseInfo']['birthday']);
            }
            if (!empty($data['baseInfo']['driverAt'])) {
                $data['baseInfo']['driverAt'] = strtotime($data['baseInfo']['driverAt']);
            }
        }
        if (isset($data['socialInfo'])) {
            if (!empty($data['socialInfo']['shihui']['regDate'])) {
                $data['socialInfo']['shihui']['regDate'] = strtotime($data['socialInfo']['shihui']['regDate']);
            }
        }
        $_filter = array('id'=>$id);
        if (!is_null($customer)) {
            if (empty($data['houseInfo'])) {
                unset($data['houseInfo']);
            }
            $isSave = $this->_repoService()->update($_filter, $data);
            // 把返回的信息中houseInfo的id转为string返回
            $cus_info = $this->_repoService()->find(['id' => $id]);
            $cus_info = $cus_info->merge();
            if ($isSave)
                return $cus_info;
            else
                return $this->_error('修改失败');
        }else {
            return $this->_error('没有找到此会员');
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //当前登录用户为操作员的话,无权限创建
        $this->authorize('destroy', new Customer());
    }

    /**
     * 获取指定客户的认领关系数据
     * @FunName: acceptRecords
     * @Param: * @param $id
     */
    public function acceptRecords($id)
    {
        $customer = Customer::find($id);
        if (is_null($customer)) {
            return $this->_error("此客户不存在");
        }
        $data = $this->_repoService()->findAcceptRecordsById($id);
        $total = count($data);
        return compact('total', 'data');
    }

}
